<template>
      <div class="app-container">
            <div class="filter-container">
                  <el-input style="width: 200px;" class="filter-item" placeholder="请输入字典编码" @keyup.enter.native="handleFilter" v-model="listQuery.dictionaryId">
                  </el-input>
                  <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">
                        搜索
                  </el-button>
                  <el-button class="filter-item" style="float:right" type="default" icon="edit" @click="handleCreate">
                        新建字典
                  </el-button>
            </div>
            <el-table :data="tableData" v-loading.body="listLoading" border fit highlight-current-row style="width: 100%">
      
                  <el-table-column align="center" label="序号" width="65">
                        <template scope="scope">
                              <span>{{scope.$index+1+(listQuery.page-1)*listQuery.limit}}</span>
                        </template>
                  </el-table-column>
      
                  <el-table-column align="left" label="字典编码">
                        <template scope="scope">
                              <span>{{scope.row.dictionaryId}}</span>
                        </template>
                  </el-table-column>
      
                  <el-table-column label="字典描述">
                        <template scope="scope">
                              <span>{{scope.row.dictionaryName}}</span>
                        </template>
                  </el-table-column>
                  <el-table-column label="操作">
                        <template scope="scope">
                              <el-button size="small" type="success" @click="handleUpdate(scope.row)">
                                    编辑
                              </el-button>
                              <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                                    删除
                              </el-button>
                        </template>
                  </el-table-column>
            </el-table>
            <div v-show="!listLoading" class="pagination-container">
                  <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
                  </el-pagination>
            </div>
            <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" style='margin-top:50px;' size="small">
                  <el-form :model="temp" :rules="rule" ref="temp" :label-width="formLabelWidth">
                        <el-form-item label="字典编码" prop="dictionaryId">
                              <el-input v-model="temp.dictionaryId" auto-complete="off" :style="inputWidthUp" :maxlength="maxlength1"></el-input>
                        </el-form-item>
      
                        <el-form-item label="字典描述" prop="dictionaryName">
                              <el-input v-model="temp.dictionaryName" auto-complete="off" :style="inputWidthUp" :maxlength="maxlength1"></el-input>
                        </el-form-item>
                  </el-form>
                  <el-form :model="tempDetail" label-position="top" :inline="true" class="demo-form-inline" :label-width="formLabelWidth" ref="tempDetail">
                        <div class="postInfo-container">
                              <el-row>
                                    <el-col :span="5">
                                          <el-form-item label="键" class="postInfo-container-item" prop="basic.dictKey" :rules="[{ required: true, message: '请输入键值', trigger: 'blur' }]">
                                                <el-input v-model="tempDetail.basic.dictKey" auto-complete="off" :style="inputWidthDown" :maxlength="maxlength2"></el-input>
                                          </el-form-item>
                                    </el-col>
      
                                    <el-col :span="5">
                                          <el-form-item label="值" class="postInfo-container-item" prop="basic.dictValue" :rules="[{ required: true, message: '请输入键值', trigger: 'blur' }]">
                                                <el-input v-model="tempDetail.basic.dictValue" auto-complete="off" :style="inputWidthDown" :maxlength="maxlength2"></el-input>
                                          </el-form-item>
                                    </el-col>
      
                                    <el-col :span="5">
                                          <el-form-item label="注释" class="postInfo-container-item">
                                                <el-input v-model="tempDetail.basic.dictDescribe" auto-complete="off" :style="inputWidthDown" :maxlength="maxlength2"></el-input>
                                          </el-form-item>
                                    </el-col>
      
                                    <el-col :span="5">
                                          <el-form-item label="排序" class="postInfo-container-item" prop="basic.orderNum" :rules="[{ required: true, message: '请输入序号' } ,{ type: 'number', message: '请输入数字' }]">
                                                <el-input v-model.number="tempDetail.basic.orderNum" auto-complete="off" :style="inputWidthDown"></el-input>
                                          </el-form-item>
                                    </el-col>
      
                                    <el-col :span="3">
                                          <el-form-item label="操作">
                                                <el-button @click="addKeyVal" >添加</el-button>
                                          </el-form-item>
                                    </el-col>
                              </el-row>
                              <el-row v-for="(item, index) in tempDetail.add" :key="item.key">
                                    <el-col :span="5">
                                          <el-form-item class="postInfo-container-item" :prop="'add.' + index + '.dictKey'" :rules="[{ required: true, message: '请输入键值', trigger: 'blur' }]">
                                                <el-input v-model="item.dictKey" auto-complete="off" :style="inputWidthDown" :maxlength="maxlength2"></el-input>
                                          </el-form-item>
                                    </el-col>
      
                                    <el-col :span="5">
                                          <el-form-item class="postInfo-container-item" :prop="'add.' + index + '.dictValue'" :rules="[{ required: true, message: '请输入键值', trigger: 'blur' }]">
                                                <el-input v-model="item.dictValue" auto-complete="off" :style="inputWidthDown" :maxlength="maxlength2"></el-input>
                                          </el-form-item>
                                    </el-col>
      
                                    <el-col :span="5">
                                          <el-form-item class="postInfo-container-item">
                                                <el-input v-model="item.dictDescribe" auto-complete="off" :style="inputWidthDown" :maxlength="maxlength2"></el-input>
                                          </el-form-item>
                                    </el-col>
      
                                    <el-col :span="5">
                                          <el-form-item class="postInfo-container-item" :prop="'add.' + index + '.orderNum'" :rules="[{ required: true, message: '请输入序号'} ,{ type: 'number', message: '请输入数字' }]">
                                                <el-input v-model.number="item.orderNum" auto-complete="off" :style="inputWidthDown"></el-input>
                                          </el-form-item>
                                    </el-col>
      
                                    <el-col :span="3">
                                          <el-form-item>
                                                <el-button @click="deleteKeyVal(index)">删除</el-button>
                                          </el-form-item>
                                    </el-col>
                              </el-row>
                        </div>
                  </el-form>
                  <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取 消</el-button>
                        <el-button type="primary" @click="create">确 定</el-button>
                  </div>
            </el-dialog>
      </div>
</template>
<script>
export default {
      data() {
            return {
                  tableData: null,
                  list: null,
                  listCopy: null,
                  total: null,
                  listLoading: true,
                  listQuery: {
                        page: 1,
                        limit: 10,
                        dictionaryId: ''
                  },
                  dialogFormVisible: false,
                  dialogStatus: '',
                  temp: {
                        dictionaryId: '',
                        dictionaryName: '',
                  },
                  tempDetail: {
                        basic: {
                              dictKey: '',
                              dictValue: '',
                              dictDescribe: '',
                              orderNum: ''
                        },
                        add: []
                  },
                  textMap: {
                        update: '编辑字典信息',
                        create: '新建字典信息'
                  },
                  inputWidthUp: {
                        width: '200px'
                  },
                  inputWidthDown: {
                        width: '120px'
                  },
                  formLabelWidth: '100px',
                  rule: {
                        dictionaryId: [
                              { required: true, message: '请输入字典编码', trigger: 'blur' }
                        ],
                        dictionaryName: [
                              { required: true, message: '请输入字典描述', trigger: 'blur' }
                        ]
                  },
                  maxlength1: 50,
                  maxlength2: 200,
            }
      },
      created() {
            this.getList();
      },
      methods: {
            getList() {
                  this.listLoading = true;
                  this.$http.get('/sys/dictionary/list')
                        .then((response) => {
                              // console.log(response);
                              if (response.code === 0) {
                                    this.list = response.data;
                                    this.listCopy = response.data;
                                    this.total = response.data.length;
                                    this.listLoading = false;
                                    this.pageChange(this.listQuery.page);
                                    // console.log(this.list);
                              }
                        })
                        .catch(function (response) {
                              console.log(response);
                        })
            },
            //搜索筛选
            handleFilter() {
                  this.listCopy = this.list.filter(item => {
                        return item.dictionaryId.indexOf(this.listQuery.dictionaryId) > -1;
                  });
                  // console.log(this.listCopy);
                  this.total = this.listCopy.length;
                  this.pageChange(this.listQuery.page);
            },
            //以下，分页函数
            handleSizeChange(val) {
                  this.listQuery.limit = val;
                  this.pageChange(this.listQuery.page);
            },
            handleCurrentChange(val) {
                  this.listQuery.page = val;
                  this.pageChange(val);
            },
            pageChange(page) {
                  this.tableData = this.listCopy.slice((page - 1) * this.listQuery.limit, page * this.listQuery.limit);
            },
            //新建信息，弹对话框
            handleCreate() {
                  this.resetTemp();
                  this.dialogStatus = 'create';
                  this.dialogFormVisible = true;
            },
            //编辑信息
            handleUpdate(row) {
                  // console.log(row);
                  this.resetTemp();
                  var url = '/sys/dictionary/listById/' + row.dictionaryId;
                  this.$http.get(url)
                        .then((response) => {
                              // console.log(response.data);                        
                              // console.log(this.tempDetail.basic);
                              response.data.forEach((item, i) => {
                                    if (i === 0) {
                                          this.tempDetail.basic = response.data[i];
                                          // console.log(this.tempDetail.basic);
                                    } else if (i > 0) {
                                          this.tempDetail.add.push(item);
                                          // console.log(this.tempDetail.add);
                                    }
                              });
                        })
                        .catch(function (response) {
                              console.log(response);
                        })
                  this.temp = Object.assign({}, row);
                  this.dialogStatus = 'update';
                  this.temp.disabled = true;
                  this.dialogFormVisible = true;
            },
            //删除信息
            handleDelete(row) {
                  const h = this.$createElement;
                  var url = '/sys/dictionary/delete/' + row.dictionaryId;
                  this.$msgbox({
                        title: '删除字典',
                        message: h('p', null, [h('span', null, '是否删除 '), h('span', { style: 'color: #f00' }, row.dictionaryName), h('span', null, ' 这个字典')]),
                        showCancelButton: true,
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                  }).then((action) => {
                        if (action === 'confirm') {
                              this.$http.delete(url)
                                    .then((response) => {
                                          if (response.code === 0) {
                                                this.showMessage("删除成功!", "success");
                                                this.getList();
                                          } else {
                                                console.log(response.msg);
                                                this.showMessage('系统错误!', 'error');
                                          }
                                    })
                                    .catch(function (response) {
                                          console.log(response)
                                    })
                              this.getList();
                        } else {
                              this.showMessage('已取消更改!', 'info');
                        }
                  }).catch(() => {
                        this.$message({
                              type: 'info',
                              message: '已取消删除'
                        });
                  });

            },
            //确认新建信息
            create() {
                  // console.log(this.temp);
                  // console.log(this.tempDetail);
                  var url = '';
                  var keyValue = [];
                  this.$refs['tempDetail'].validate((valid1) => {
                        if (valid1) {
                              this.$refs['temp'].validate((valid2) => {
                                    if (valid2) {
                                          if (this.dialogStatus === 'create') {
                                                keyValue.push(this.tempDetail.basic);
                                                if (this.tempDetail.add.length > 0) {
                                                      this.tempDetail.add.forEach((item) => {
                                                            keyValue.push(item);
                                                      });
                                                }
                                                url = '/sys/dictionary/add';
                                                this.$http.post(url, {
                                                      "dictionaryId": this.temp.dictionaryId,
                                                      "dictionaryName": this.temp.dictionaryName,
                                                      "keys": keyValue
                                                })
                                                      .then((response) => {
                                                            if (response.code === 0) {
                                                                  this.dialogFormVisible = false
                                                                  this.showMessage('创建成功!', 'success');
                                                                  this.getList();
                                                            } else {
                                                                  this.dialogFormVisible = false
                                                                  console.log(response.msg);
                                                                  this.showMessage('系统错误!', 'error');
                                                            }
                                                      }).catch((response) => {
                                                            console.log(response);
                                                      })
                                          } else {
                                                keyValue.push(this.tempDetail.basic);
                                                if (this.tempDetail.add.length > 0) {
                                                      this.tempDetail.add.forEach((item) => {
                                                            keyValue.push(item);
                                                      });
                                                }
                                                url = '/sys/dictionary/update';
                                                this.$http.put(url, {
                                                      "dictionaryId": this.temp.dictionaryId,
                                                      "dictionaryName": this.temp.dictionaryName,
                                                      "keys": keyValue
                                                })
                                                      .then((response) => {
                                                            if (response.code === 0) {
                                                                  this.dialogFormVisible = false
                                                                  this.showMessage('修改成功!', 'success');
                                                                  this.getList();
                                                            } else {
                                                                  this.dialogFormVisible = false
                                                                  console.log(response.statusText);
                                                                  this.showMessage('系统错误!', 'error');
                                                            }
                                                      }).catch((response) => {
                                                            console.log(response);
                                                      })
                                          }
                                    } else {
                                          console.log('error submit!!');
                                          return false;
                                    }
                              });
                        }
                  });
            },
            //置空temp数据，防止绑定信息
            resetTemp() {
                  if (this.$refs['temp']) {
                        this.$refs['temp'].resetFields();
                  };
                  if (this.$refs['tempDetail']) {
                        this.$refs['tempDetail'].resetFields();
                  };
                  this.temp = {
                        dictionaryId: '',
                        dictionaryName: '',
                  };
                  this.tempDetail = {
                        basic: {
                              dictKey: '',
                              dictValue: '',
                              dictDescribe: '',
                              orderNum: ''
                        },
                        add: []
                  }
            },
            //提示消息
            showMessage(msg, type) {
                  this.$message({
                        message: msg,
                        type: type
                  });
            },
            // 添加 键值
            addKeyVal() {
                  this.tempDetail.add.push({
                        dictKey: '',
                        dictValue: '',
                        dictDescribe: '',
                        orderNum: ''
                  });
                  // console.log(this.tempDetail);
            },
            //删除键值
            deleteKeyVal(index) {
                  // console.log(index);
                  this.tempDetail.add.splice(index, 1);
            }
      }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.filter-container {
      padding-bottom: 10px;
      .filter-item {
            margin-bottom: 10px;
      }
}

.pagination-container {
      margin-top: 30px;
}
</style>